/*************************************************************************
 *
 * SerialTask
 * 
 * (c) Ales Povalac, alpov@alpov.net, http://www.alpov.net/
 * 
 *************************************************************************
 *
 * $Id: serial.c 119 2007-01-22 17:35:57Z Ales $
 * 
 *************************************************************************/         

#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <avr/pgmspace.h>
#include "../avrx/avrx.h"
#include "../avrx/AvrXFifo.h"
#include "hw.h"
#include "serial.h"
#include "serial_hnds.h"
#include "data.h"
#include "menu.h"
#include "locate.h"

#include "../global/serial.c"

Mutex Initialized;


/*************************************************************************
 * odeslani udaju, vyuziva RWDATA_R_Handler()
 * funkce provedeni updatu volana z menu 
 *************************************************************************/ 
void Serial_RWDATA_W(unsigned char item)
{
    PACKET_HEADER ph;
    TimerControlBlock timer;
    
    timer.semaphore = SEM_PEND;
    
    ph.src = ADDR_SERVER; // handler -> dest=src
    ph.item_hi = item;
    ph.item_lo = 0;
    
    for (int i = 0; i < PACKET_TX_TRIES; i++) {
        RWDATA_R_Handler(&ph, NULL, 0);
        if (SerialWaitAck(ph.seq))
            return;
        AvrXDelay(&timer, PACKET_RAND_DELAY);
    }
    MenuMessage(MSG_COMERR);
}


/*************************************************************************
 * zadost o inicializaci, vyuzivano pri startu 
 *************************************************************************/ 
void Serial_INIT_R(void)
{
    PACKET_HEADER ph;
    
    ph.dest = ADDR_SERVER;
    ph.src = ADDR_TERMINAL;
    ph.cmd = CMD_INIT_READ;
    ph.item_hi = ITEM_ALL;
    ph.item_lo = 0;
    
    SerialSendPacket(&ph, NULL, 0, 1);
}

